package com.aaa.aop;

import com.aaa.aop.annotation.Log;
import com.aaa.entity.OperLog;
import com.aaa.service.impl.OperLogServiceImpl;
import com.aaa.util.AccountName;
import com.aaa.util.WebUtil;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @BelongsPackage: com.aaa.aop
 * @Description: 1.0
 * @CreateTime: 2023-03-29  19:53
 * @Author: ql
 */
@Component
@Aspect
public class OperLogAspect {
    //定义切点
    @Pointcut(value = "@annotation(com.aaa.aop.annotation.Log)")
    public void poincut(){
    }

    @Autowired
    private OperLogServiceImpl operLogService;
    @Autowired
    private AccountName accountName;

    @AfterReturning(value = "poincut()",returning = "res")
    public void afterReturning(JoinPoint joinPoint, Object res){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        OperLog operLog = new OperLog();
        Method method = methodSignature.getMethod(); //获取使用Log注解的方法对象
        Log log = method.getAnnotation(Log.class);
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = WebUtil.getRequest();
        String remoteAddr = request.getRemoteAddr();
        String username = accountName.getAccountName();
        String requestMethod = request.getMethod();
        String title = log.title();
        String businessType = log.business_type();
        String methodName = method.getName();
        String oper_url = request.getServletPath();
        String oper_location=remoteAddr.startsWith("192.168.")?"内网IP":"外网IP";
        String oper_param= JSON.toJSONString(args);
        String json_result=JSON.toJSONString(res);
        String status="0";
        Date oper_time=new Date();

        operLog.setTitle(title);
        operLog.setBusinessType(businessType);
        operLog.setMethod(methodName);
        operLog.setRequestMethod(requestMethod);
        operLog.setOperatorType(log.operator_type());
        operLog.setOperName(username);
        operLog.setOperUrl(oper_url);
        operLog.setOperIp(remoteAddr);
        operLog.setOperLocation(oper_location);
        operLog.setOperParam(oper_param);
        operLog.setJsonResult(json_result);
        operLog.setStatus(status);
        operLog.setOperTime(oper_time);

        Boolean insert = operLogService.insert(operLog);
        System.out.println("是否操作日志成功============ " + insert);

    }
}
